//
//  BBSViewController.m
//  FuturesProject
//
//  Created by 陈赞荣 on 2017/10/26.
//  Copyright © 2017年 czr. All rights reserved.
//

#import "BBSViewController.h"
#import "loginVC.h"
#import "AllCommentVC.h"

@interface BBSViewController ()<UIScrollViewDelegate,UITextViewDelegate,LZBInifiteScrollViewDelegate>
@property(strong,nonatomic)UIView           *viewTop;
@property(strong,nonatomic)UIWebView        *mWebView;
@property(strong,nonatomic)NSMutableArray   *dataArr;
@property(strong,nonatomic)UIScrollView     *scrollView;
@property(nonatomic,strong) UIButton        *toolButton;//右侧按钮
@property(nonatomic,strong)NSDictionary     *dic;
@property (nonatomic,strong)UIImageView *likeImageV;

@property(strong,nonatomic)UIView                *mHeadrView;//头部轮播视图

@property(strong,nonatomic)   LZBInifiteScrollView         *mBannerView;//轮播第三方类


@end

@implementation BBSViewController

-(instancetype)init
{
    self=[super init];
    if (self)
    {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"详情";
    
    [self getData];
    self.dataArr = [[NSMutableArray alloc]init];
    

    self.view.backgroundColor=[UIColor whiteColor];
    
    self.toolButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.toolButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.toolButton setTitleColor:RGBCOLOR(0x25, 0x43, 0x7f) forState:UIControlStateNormal];
    [self.toolButton addTarget:self action:@selector(toolButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.toolButton.frame = CGRectMake(0, 0, 40, 15);
    self.toolButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.toolButton setTitle:@"评论" forState:UIControlStateNormal];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:self.toolButton];
        self.navigationItem.rightBarButtonItem = buttonItem;
    
    
    
   
    // Do any additional setup after loading the view.
}

#pragma mark 请求行情股市数据
- (void)getData
{
    [SVProgressHUD showWithStatus:@"请求中..."];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    param[@"split"] = @"on";
    NSString *aBBSDetailsUrl = [NSString stringWithFormat:@"api/topic/%@",self.mUrlStr];
    NSLog(@"参数:%@",self.mUrlStr);
    [HTTPManagers postBBSWithURL:aBBSDetailsUrl params:param success:^(id json)
    {
        if ([json[@"code"] integerValue] == 0)
        {
            self.dic = json[@"message"];
            [self createView];
        }else{
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
        }
        [SVProgressHUD dismiss];
        
    } failure:^(NSError *error)
    {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"请检查网络"];
    }];
}


-(void)toolButtonClick
{
//    CommentsViewController *vc=[[CommentsViewController alloc]init];
//    vc.stringID=self.dic[@"Id"];
//    [self.navigationController pushViewController:vc animated:YES];
    
    loginVC *vc = [loginVC new];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 主视图
- (void)createView{
    
    self.scrollView=[[UIScrollView alloc]initWithFrame:RectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
   
    [self.view addSubview:self.scrollView];
    
    self.viewTop=[[UIView alloc]initWithFrame:RectMake(0, 0, SCREEN_WIDTH, 60)];
    self.viewTop.backgroundColor=[UIColor whiteColor];
    [self.scrollView addSubview:self.viewTop];
    
    UILabel *lableTitle=[[UILabel alloc]initWithFrame:RectMake(10, 10, SCREEN_WIDTH-20, 10)];
    NSString *titleStr = [self.mtitle stringByReplacingOccurrencesOfString:@" " withString:@""];
    titleStr = [titleStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    lableTitle.text=titleStr;
    lableTitle.textColor=HWColor(102, 102, 102);
    lableTitle.textAlignment=NSTextAlignmentCenter;
    lableTitle.font=[UIFont systemFontOfSize:16];
    [self.viewTop addSubview:lableTitle];
    
    UILabel *timeTitle=[[UILabel alloc]initWithFrame:RectMake(10, 40, SCREEN_WIDTH/2, 10)];
    timeTitle.font=[UIFont systemFontOfSize:9];
    NSString *aStartTimeStr = [self changeTimeStr2Date:[self.dic valueForKey:@"Creation"]];
    NSString *aTime = [NSString stringWithFormat:@"%@",aStartTimeStr];
    timeTitle.text = aTime;
    timeTitle.textColor=HWColor(153, 153, 153);
    [self.viewTop addSubview:timeTitle];
    
    UIButton *btnLike=[UIButton buttonWithType:UIButtonTypeCustom];
    btnLike.frame=RectMake(SCREEN_WIDTH-50, 15, 40 , 40);
//    [btnLike setImage:[UIImage imageNamed:@"qingdianzan.png"] forState:UIControlStateNormal];
//    [btnLike setImage:[UIImage imageNamed:@"yidianzan.png"] forState:UIControlStateSelected];
    [btnLike addTarget:self action:@selector(likeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _likeImageV = [[UIImageView alloc]init];
    _likeImageV.image = [UIImage imageNamed:@"qingdianzan.png"];
    _likeImageV.contentMode = UIViewContentModeScaleAspectFit;
    [btnLike addSubview:_likeImageV];
    
    [_likeImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(btnLike);
        make.width.mas_equalTo(25);
        make.height.mas_equalTo(25);
    }];
    [self.viewTop addSubview:btnLike];
    
    //头部视图
    self.mHeadrView = [[UIView alloc]initWithFrame:RectMake(0, 60, SCREEN_WIDTH, 160)];
    self.mHeadrView.backgroundColor = BackgroundColor;
    
    
    self.mBannerView = [[LZBInifiteScrollView alloc]init];
    self.mBannerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 160);
    [self.mHeadrView addSubview:self.mBannerView];
    self.mBannerView.foucsDelegate = self;
    
   
    
    UITextView *textView=[[UITextView alloc]init];
    textView.font=[UIFont systemFontOfSize:14];
    textView.text=[[self.dic valueForKey:@"Content"]valueForKey:@"Content"];
    textView.editable=NO;
    
    CGFloat textY;
    textY=[self getLabelHeightWithString:textView.text andWidth:SCREEN_WIDTH-10 andFont:[UIFont systemFontOfSize:14]];
    
    self.scrollView.contentSize=CGSizeMake(SCREEN_WIDTH,textY+330 );
    textView.frame=RectMake(10, 220, SCREEN_WIDTH-10, textY+100);

    
    textView.textColor=[UIColor blackColor];
    [self.scrollView addSubview:textView];
    
    
    NSString *aImageStr = [NSString stringWithFormat:@"%@",self.dic[@"Content"][@"Images"]];
    if ([aImageStr isEqualToString:@"<null>"]) {
        self.mHeadrView.hidden=YES;
        self.scrollView.contentSize=CGSizeMake(SCREEN_WIDTH,textY+330-160 );
        textView.frame=RectMake(10, 50, SCREEN_WIDTH-10, textY+100);
    }else{
        self.mHeadrView.hidden=NO;
        
        NSArray * arr = @[@"banner1",@"banner2-",@"banner3"];
        
//        aImageStr = [aImageStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
//        aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//        aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//        aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
//         aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
//        aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@")" withString:@""];
//        aImageStr = [aImageStr stringByReplacingOccurrencesOfString:@" " withString:@""];
//
//        NSArray * arr= [aImageStr componentsSeparatedByString:@","];
        self.mBannerView.images = arr;
        [self.scrollView addSubview:self.mHeadrView];
    }

    
}

//获取高度,传入文本框的宽度和字号以及内容
-(CGFloat)getLabelHeightWithString:(NSString *)text andWidth:(CGFloat)width andFont:(UIFont *)font{
    UITextView* textViewTemple = [[UITextView alloc]init];
    textViewTemple.text = text;
    //    [textViewTemple setFont:[UIFont systemFontOfSize:14]];
    [textViewTemple setFont:font];
    //     获取该段attributedString的属性字典
    CGSize textSize = [textViewTemple.text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                                     attributes:[NSDictionary dictionaryWithObjectsAndKeys:textViewTemple.font,NSFontAttributeName, nil]         // 文字的属性
                                                        context:nil].size;
    return textSize.height;
}

-(NSString *)changeTimeStr2Date:(NSString *)string{
    NSTimeInterval time=[string doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}


//点赞按钮响应函数
-(void)btnLikeAction:(UIButton *)btn
{
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    param[@"tid"] = self.dic[@"Id"];
    [SVProgressHUD showWithStatus:@"请求中..."];
    [HTTPManagers postBBSWithURL:@"api/topic/like" params:param success:^(id json) {
        if ([json[@"code"] intValue] == 0) {
           
                [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
        
        }
        
        if([json[@"message"] isEqualToString:@"unrepeatable like"])
        {
          
                [SVProgressHUD showErrorWithStatus:@"您已经点赞过"];
           
        }
        if ([json[@"message"] isEqualToString:@"user not login"])
        {
            [SVProgressHUD showErrorWithStatus:@"您尚未登录，请先登录"];
            loginVC *vc=[[loginVC alloc]init];
            [self.navigationController pushViewController: vc animated:YES];
            
        }
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"请检查网络"];
    }];


    
    
}
-(void)likeClick:(UIButton *)sender{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"tid"] = self.dic[@"Id"];
    [HTTPManagers postLikeWithURL:@"like" params:params success:^(id json) {
        if ([json[@"message"]isEqualToString:@"unrepeatable like"]) {
            [SVProgressHUD showErrorWithStatus:@"您已点过赞～" maskType:SVProgressHUDMaskTypeBlack];
            _likeImageV.image = [UIImage imageNamed:@"yidianzan.png"];
            
            
            return ;
        }
        if ([json[@"code"]integerValue]==1) {
            [SVProgressHUD showErrorWithStatus:@"请重新登陆" maskType:SVProgressHUDMaskTypeBlack];
            loginVC *vc = [loginVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            
            
            
        }
        if ([json[@"code"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
            _likeImageV.image = [UIImage imageNamed:@"yidianzan.png"];
            
        }

    } failure:^(NSError *error) {
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
